const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    // 查询用户信息
    const result = await db.collection('users').where({
      _openid: openid
    }).get()
    
    if (result.data.length === 0) {
      // 用户不存在，返回错误
      return {
        success: false,
        message: '用户不存在',
        error: 'USER_NOT_FOUND'
      }
    }
    
    const userData = result.data[0]
    
    // 检查用户状态
    if (userData.status !== 1) {
      return {
        success: false,
        message: '用户已被禁用',
        error: 'USER_DISABLED'
      }
    }
    
    // 构建返回数据
    let responseData = { ...userData }
    
    try {
      // 查询会员等级信息
      if (userData.memberLevel !== undefined) {
        const memberLevelResult = await db.collection('member_levels')
          .where({
            level: userData.memberLevel
          })
          .limit(1)
          .get()
        
        if (memberLevelResult.data.length > 0) {
          const levelInfo = memberLevelResult.data[0]
          responseData.memberLevelInfo = {
            level: userData.memberLevel,
            name: levelInfo.name || '普通会员'
          }
        } else {
          // 找不到对应等级，使用默认值
          responseData.memberLevelInfo = {
            level: userData.memberLevel,
            name: '普通会员'
          }
        }
      } else {
        // 用户没有会员等级字段
        responseData.memberLevelInfo = {
          level: 0,
          name: '普通会员'
        }
      }
    } catch (levelError) {
      console.warn('查询会员等级信息失败:', levelError)
      // 如果查询失败，仍返回用户数据，但使用默认等级信息
      responseData.memberLevelInfo = {
        level: userData.memberLevel || 0,
        name: '普通会员'
      }
    }
    
    return {
      success: true,
      data: responseData
    }
    
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return {
      success: false,
      message: error.message || '获取用户信息失败'
    }
  }
}